﻿using Protocol.Code;
using Script.Framework;
using Script.Net.Impl;
using UnityEngine;

namespace Script.Net
{
    /// <summary>
    /// 网络的消息中心类
    /// 负责将下层网络的消息(from ClientPeer)分发到各个逻辑模块（Handler）
    /// </summary>
    public class NetManager : ManagerBase
    {
        public static NetManager instance;


        private void Start()
        {
            Connected("127.0.0.1", 6666);
        }


        private ClientPeer client;


        private void Connected(string ip, int port)
        {
            client = new ClientPeer(ip, port);
        }


        private void Update()
        {
            if (client == null)
            {
                return;
            }

            while (client.SocketMsgQueue.Count > 0)
            {
                SocketMsg msg = client.SocketMsgQueue.Dequeue();

                // 操作这个msg
                ProcessSocketMsg(msg);
            }
        }

        #region 处理客户端内部 给服务器发送消息的事件

        private void Awake()
        {
            instance = this;

            Add(0, this);
        }

        /// <summary>
        /// 借助ClientPeer(Socket封装类）给服务器发送消息
        /// </summary>
        /// <param name="eventCode"></param>
        /// <param name="message"></param>
        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case 0:
                    client.Send(message as SocketMsg);
                    break;
            }
        }

        #endregion

        #region 处理接受到的服务器的消息

        private readonly HandlerBase accountHandler = new AccountHandler();
        private readonly HandlerBase userHandler = new UserHandler();
        private readonly HandlerBase matchHandler = new MatchHandler();
        private readonly HandlerBase chatHandler = new ChatHandler();
        private readonly HandlerBase fightHandler = new FightHandler();

        /// <summary>
        /// 接受网络的消息
        /// </summary>
        /// <param name="msg"></param>
        private void ProcessSocketMsg(SocketMsg msg)
        {
            switch (msg.OpCode)
            {
                case OpCode.ACCOUNT:
                    accountHandler.OnReceive(msg.SubCode, msg.Value);
                    break;
                case OpCode.USER:
                    userHandler.OnReceive(msg.SubCode, msg.Value);
                    break;
                case OpCode.MATCH:
                    matchHandler.OnReceive(msg.SubCode, msg.Value);
                    break;
                case OpCode.CHAT:
                    chatHandler.OnReceive(msg.SubCode, msg.Value);
                    break;
                case OpCode.FIGHT:
                    fightHandler.OnReceive(msg.SubCode, msg.Value);
                    break;
                default:
                    Debug.LogError("The have a error");
                    break;
            }
        }

        #endregion
    }
}